Day 11 - Find and replace text
38
$ grep "elephant" examples.txt | sed s/"ele"/"oli"/
oliphant
I tend to avoid the / in my sed command because many times I run it on file paths, which contain
the /, thus making the command fail. Obviously, the comma doens’t work well if your main activity
is to process comma-separated values files (CSV), so your mileage may vary. Just to see that sed
really doesn’t mind the separation character, try to execute
$ grep "elephant" examples.txt | sed svelevoliv
oliphant
To be clear, not only I do not endorse such a cryptic syntax, but if you dare to use it and tell people
that I told you to do so I will grep ${you} universe.txt | sed s,"${you}","void",. Friendly
advice. =) You can also notice from this last example that quotes are optional. As usual, I believe
they make the whole command easier to read, so my suggestion is to use them always.
By default, sed will replace only the first occurrence of the search string, and if you want to replace
all of them you need to use the g option
$ echo "abracadabra" | sed s,"a","_",
_bracadabra
$ echo "abracadabra" | sed s,"a","_",g
_br_c_d_br_
One interesting feature of sed is that the replacement pattern can contain the matched pattern,
which avoids repetitions if we need to reuse it
$ echo "abracadabra" | sed s,"a","&-",g
a-bra-ca-da-bra-
This will be superseded by groups and backreferences as soon as we will learn regular expressions,
but for the time being it’s a nice trick to learn.
Exercises
There are not many interesting exercises to do with grep and sed in this simple form. Be sure to
practice their different options, though, as they will come handy.